<template>
	<view class="chat-container">
		<!-- 原有头像区域 -->
		<view class="avatar-section" v-if="showComponent && isAutoSound" @click="showControlPanel = true">
			<view class="avatar-container">
				<image
					class="avatar"
					:class="isAnimating ? 'avatar-animated' : ''"
					:src="currentVoice ? currentVoice.avatarUrl : ''"
					mode="aspectFill"
					ref="avatar"
					:style="avatarStyle"
				></image>
				<view class="playing-indicator" v-if="currentPlayingId !== null">
					<uni-icons type="sound-filled" color="#fff" size="16"></uni-icons>
				</view>
				<view class="control-panel">
					<view class="control-btn" @click.stop="pause">
						<image class="control-img" :src="isPlaying? '/static/pause.png':'/static/play1.png' " mode=""></image>
					</view>

					<view class="control-btn" @click.stop="closeAutoPlay">
						<uni-icons type="closeempty"  size="13"></uni-icons>
					</view>
				</view>
			</view>
		</view>


	</view>
</template>
<script>
export default {
	props: {
		newMsg: {
			type: Object,
			default: () => ({})
		}
	},
	data() {
		return {
			voiceMessageList: [], // 语音消息队列
			currentPlayingId: null, // 当前播放的语音ID
			currentPlayIndex: -1, // 当前播放索引
			innerAudioContext: null, // 音频实例
			currentVoice: null, // 当前播放的语音详情
			rotateAnimation: null, // 存储动画实例
			isAnimating: false, // 控制动画启停
			animationTimer: null,
			avatarStyle: { boxShadow: '0 0 15rpx #55aaff' },
			showControlPanel: false,
			showComponent: false,
			isPlaying:false
		};
	},
	computed: {
		isAutoSound() {
			return this.$store.state.msg.stateConfig?.autoPlay ?? true;
		}
	},

	mounted() {
		this.initAudioContext();
	},
	watch: {
		newMsg: {
			handler(newMsg) {
				this.initVoice(newMsg);
				console.log('声音进来了。。。。。。。。。。。');
			}
		}
	},
	beforeDestroy() {
		// 清理资源
		if (this.innerAudioContext) {
			this.innerAudioContext.stop();
			this.innerAudioContext.destroy();
		}
		if (this.animationTimer) {
			clearTimeout(this.animationTimer);
		}

		this.stopRotate();
	},

	methods: {
		// 下一条语音
		nextVoice() {
			if (this.currentPlayIndex < this.voiceMessageList.length - 1) {
				this.currentPlayIndex++;
				const nextMsg = this.voiceMessageList[this.currentPlayIndex];
				this.autoPlayVoice(nextMsg);
				this.showComponent = true; // 显示头像
			} else {
				uni.showToast({ title: '已是最后一条', icon: 'none' });
			}
		},

		initVoice(res) {
			if (res.messageType === 1 && res.content?.voicePath) {
				const voiceMsg = {
					id: res.timestamp,
					voiceUrl: res.content.voicePath,
					voiceDuration: res.duration || 0,
					avatarUrl: res.nicPic?.url || '',
					isSelf: res.senderId === this.$store.state.msg.user.userId
				};

				if (!voiceMsg.isSelf) {
					this.voiceMessageList.push(voiceMsg);
					if (this.currentPlayIndex === -1) {
						this.showComponent = true; // 改为 showComponent
						this.$nextTick(() => {
							this.autoPlayVoice(voiceMsg);
						});
					}
				}
			}
		},

		startRotate() {
			if (this.isAnimating || !this.$refs.avatar) return;
			this.isAnimating = true;

			const avatar = this.$refs.avatar;
			// 注意：在NVUE中，我们需要使用weex的animation模块
			const animation = uni.requireNativePlugin('animation');
			animation.transition(
				avatar,
				{
					styles: {
						transform: 'rotate(0deg)',
						transformOrigin: 'center center'
					},
					duration: 0 // 立即将初始位置设为0
				},
				() => {
					// 初始设置完成后，开始循环动画
					const rotate = () => {
						if (!this.isAnimating) return;
						animation.transition(
							avatar,
							{
								styles: {
									transform: 'rotate(360deg)'
								},
								duration: 2000,
								timingFunction: 'linear'
							},
							() => {
								// 动画完成，重置并开始下一次
								if (this.isAnimating) {
									animation.transition(
										avatar,
										{
											styles: {
												transform: 'rotate(0deg)'
											},
											duration: 0
										},
										rotate
									);
								}
							}
						);
					};
					rotate();
				}
			);
		},

		stopRotate() {
			this.isAnimating = false;
			if (this.$refs.avatar) {
				const animation = uni.requireNativePlugin('animation');
				animation.transition(this.$refs.avatar, {
					styles: {
						transform: 'rotate(0deg)',
						boxShadow: 'none' // 清除阴影
					},
					duration: 0
				});
			}
		},

		// 初始化音频上下文
		initAudioContext() {
			if (this.innerAudioContext) return; // 避免重复创建
			const _this = this;
			this.innerAudioContext = uni.createInnerAudioContext();
			this.innerAudioContext.onEnded(() => {
				this.isPlaying=false
				this.currentPlayIndex++;
				if (this.currentPlayIndex < this.voiceMessageList.length) {
					_this.autoPlayVoice(this.voiceMessageList[this.currentPlayIndex]);
					_this.showComponent = true; // 播放下一条时，显示组件主体
				} else {
					_this.resetState(false); // 传入 false，不关闭控制面板
					_this.showComponent = false; // 只隐藏组件主体
					// 不设置 showControlPanel = false，保留弹窗
				}
			});
			this.innerAudioContext.onError((err) => {
				this.isPlaying=false
				console.error('语音播放失败:', err);
				uni.showToast({ title: '播放失败', icon: 'none' });
				this.resetState(false); // 不关闭控制面板
				this.showComponent = false; // 只隐藏组件主体
			});
		},
		resetState(closePanel = true) {
			this.showComponent = false; // 隐藏组件主体
			setTimeout(() => {
				this.currentPlayingId = null;
				this.currentVoice = null;
				this.currentPlayIndex = -1;
				this.voiceMessageList = [];
				this.stopRotate();
				// 只有传入 true 时，才关闭控制面板（如点击“关闭自动播放”）
				if (closePanel) {
					this.showControlPanel = false;
				}
			}, 100);
		},
		closeAutoPlay() {
			this.$store.commit('msg/setStateConfig', {
				...this.$store.state.msg.stateConfig,
				isSound: 0
			});
			this.resetState(true); // 关闭控制面板
			uni.showToast(
				{
					title: '声音自动播放已关闭',
					position: 'center',
					icon: 'none'
				},
				1500
			);
		},

		// 上一条/下一条：播放时显示组件主体
		prevVoice() {
			if (this.currentPlayIndex > 0) {
				this.currentPlayIndex--;
				const prevMsg = this.voiceMessageList[this.currentPlayIndex];
				this.autoPlayVoice(prevMsg);
				this.showComponent = true; // 显示头像
			} else {
				uni.showToast({ title: '已是第一条', icon: 'none' });
			}
		},
		// 自动播放语音
		autoPlayVoice(voiceMsg) {
			if (!voiceMsg) return;

			this.innerAudioContext.stop();
			this.currentPlayingId = voiceMsg.id;
			this.currentVoice = voiceMsg;
			this.currentPlayIndex = this.voiceMessageList.findIndex((msg) => msg.id === voiceMsg.id);

			// 关键：用 $nextTick 等待元素渲染，再设置阴影
			this.$nextTick(() => {
				if (this.$refs.avatar) {
					// 用 animation 插件设置阴影，而非 setStyle
					const animation = uni.requireNativePlugin('animation');
					animation.transition(
						this.$refs.avatar,
						{
							styles: {
								boxShadow: '0 0 15rpx #55aaff'
							},
							duration: 0 // 立即生效
						},
						() => {} // 回调可选
					);
				}
				this.startRotate();
			});

			this.innerAudioContext.src = voiceMsg.voiceUrl;
			this.innerAudioContext.play();
			this.isPlaying=true
		}
	},
	pause(){
		if(this.initAudioContext.paused){
			this.innerAudioContext.play()
		}else{
			this.initAudioContext.pause()
		}
		
	}
};
</script>

<style lang="scss" scoped>
.chat-container {
	position: fixed;
	left: 30rpx;
	bottom: 80rpx;
	z-index: 999;
    padding: 20rpx 20rpx;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.avatar-section {
	display: flex;
	background-color: #f5f5f5;
	    padding: 20rpx 20rpx;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
	align-items: center;
	/*#ifndef APP-PLUS-NVUE*/
	gap: 10rpx;
	/*#endif*/ // 补全闭合注释！之前漏了这行
}

.avatar-container {
	border-radius: 50%;
	position: relative;
}

.avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	object-fit: cover;
	border: 2rpx solid #eee;
	display: flex;
	transform-origin: center center;
}

/* 添加动画类 */
.avatar-animated {
	animation: rotate 2s linear infinite;
}

@keyframes rotate {
	from {
		transform: rotate(0deg);
	}
	to {
		transform: rotate(360deg);
	}
}

.playing-indicator {
	position: absolute;
	top: 0;
	right: 0;
	width: 32rpx;
	height: 32rpx;
	border-radius: 50%;
	background-color: #55aaff;
	display: flex;
	align-items: center;
	justify-content: center;
}

// 控制面板弹窗
.control-panel {
	
	display: flex;
	width: 100%;
	margin-top: 15rpx;
	justify-content: space-between;
}

// 功能按钮
.control-btn {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 10rpx;
	cursor: pointer;
	.control-img{
		width: 24rpx;
		height: 24rpx;
		
	}
}

.btn-text {
	font-size: 22rpx;
	color: #333;
}



.btn-text {
	color: #fff;
}
</style>
